package com.sizu.web;


import com.sizu.common.dto.FastDFSFile;
import com.sizu.common.vo.ResultEntity;
import com.sizu.entity.CgAlbum;
import com.sizu.service.ICgAlbumService;
import com.sizu.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 高旌洋
 * @since 2020-03-24
 */
@RestController
@RequestMapping("/file/cgAlbum")
public class CgAlbumController {

    @Autowired
    private ICgAlbumService iCgAlbumService;

    /***
     * 查询Album全部数据
     * @return
     */
    @GetMapping
    public ResultEntity findAll() {
        List<CgAlbum> cgAlbums = iCgAlbumService.selectList(null);
        return ResultEntity.ok(cgAlbums);
    }

    /**
     * 返回 图片的全路径
     *
     * @param file 页面的文件对象
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam(value = "file") MultipartFile file) {
        try {

            //1. 创建图片文件对象(封装)
            FastDFSFile fastdfsfile = new FastDFSFile(
                    file.getOriginalFilename(),//原来的文件名  1234.jpg
                    file.getBytes(),//文件本身的字节数组
                    StringUtils.getFilenameExtension(file.getOriginalFilename())
            );

            //2. 调用工具类实现图片上传
            String[] upload = FastDFSClient.upload(fastdfsfile);

            //String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            return FastDFSClient.getTrackerUrl() + "/" + upload[0] + "/" + upload[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
